package com.zunipe.ftpe;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FTPScanner {
    private final FTPClientWrapper mFtpClientWrapper;
    private final List<String> mPaths;

    public FTPScanner(FTPClientWrapper ftpClientWrapper, List<String> paths) {
        this.mFtpClientWrapper = ftpClientWrapper;
        this.mPaths = paths;
    }

    public List<ScannerResult> scanFile() throws IOException {
        FTPClient ftpClient = mFtpClientWrapper.getFtpClient();
        List<ScannerResult> result = new ArrayList<>();

        for (String path : mPaths) {
            FTPFile[] ftpFiles = ftpClient.listDirectories(path);
            Arrays.sort(ftpFiles, (a, b) -> {
                long ta = a.getTimestamp().getTimeInMillis();
                long tb = b.getTimestamp().getTimeInMillis();
                if (ta == tb) {
                    return 0;
                }
                return ta < tb ? 1 : -1;
            });
            result.add(new ScannerResult(ftpFiles.length, path, Arrays.asList(ftpFiles)));
        }
        return result;
    }
}
